package com.scheduled;

import com.mrobuy.jd.JdClientFactory;
import com.mrobuy.jdvc.dao.JDAccountDao;
import com.mrobuy.jdvc.entity.JDAccount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * appkey 的 access tokeb 定时刷新
 */
@Component
public class AccessokenTask {

    private static Logger LOG = LoggerFactory.getLogger(AccessokenTask.class);

    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private JDAccountDao jdAccountDao;

    private static final String URL_TEMP = "https://open-oauth.jd.com/oauth2/refresh_token?refresh_token=%s&app_key=%s&app_secret=%s&grant_type=refresh_token";

    private static final long THRESHOLD = 12*3600*1000; // 12小时

    @Scheduled(fixedRate = 1000*60*10)
    public void reportCurrentTime() {

        long nowMillis = Calendar.getInstance().getTimeInMillis();


        Calendar calendar = Calendar.getInstance();

        RestTemplate restTemplate = new RestTemplate();


        List<JDAccount> accounts =  jdAccountDao.list();
        for (JDAccount account : accounts) {

            calendar.setTimeInMillis(account.getTime());

            Date lastUpdate = calendar.getTime();
            if ( account.getTime() + THRESHOLD > nowMillis ) {
                LOG.info("[{}][12小时内更新, 跳过]最后更新时间: {}", account.getName() , dateFormat.format(lastUpdate));
                continue;
            }

            LOG.info(account.getName() + "]最后更新时间: " + dateFormat.format(lastUpdate));

            String url = String.format(URL_TEMP, account.getRefresh_token(), account.getAppkey(), account.getAppsecret());
            Token token = restTemplate.getForObject(url, Token.class);

            account.setTime(token.getTime());
            account.setAccess_token(token.getAccess_token());
            account.setRefresh_token(token.getRefresh_token());
            account.setExpires_in(token.getExpires_in());

            jdAccountDao.updatess(account);

            JdClientFactory.clean();
        }

    }

    static class Token {

        /**
         * access_token : 1d4a07ea9743455d99c2f7f63e2f7971a3zw
         * expires_in : 31536000
         * refresh_token : 27c1db3d5fc74ef992314b616cc1efc8rim2
         * scope : snsapi_base
         * open_id : xrmaB94jFbpyRUhVEIwpdTQJrBlR3kJupxln__mvCCw
         * uid : 9457503810
         * time : 1607569106421
         * token_type : bearer
         * code : 0
         */

        private String access_token;
        private int expires_in;
        private String refresh_token;
        private String scope;
        private String open_id;
        private String uid;
        private long time;
        private String token_type;
        private int code;

        public String getAccess_token() {
            return access_token;
        }

        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }

        public int getExpires_in() {
            return expires_in;
        }

        public void setExpires_in(int expires_in) {
            this.expires_in = expires_in;
        }

        public String getRefresh_token() {
            return refresh_token;
        }

        public void setRefresh_token(String refresh_token) {
            this.refresh_token = refresh_token;
        }

        public String getScope() {
            return scope;
        }

        public void setScope(String scope) {
            this.scope = scope;
        }

        public String getOpen_id() {
            return open_id;
        }

        public void setOpen_id(String open_id) {
            this.open_id = open_id;
        }

        public String getUid() {
            return uid;
        }

        public void setUid(String uid) {
            this.uid = uid;
        }

        public long getTime() {
            return time;
        }

        public void setTime(long time) {
            this.time = time;
        }

        public String getToken_type() {
            return token_type;
        }

        public void setToken_type(String token_type) {
            this.token_type = token_type;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }
    }
}
